package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * 用户控制器
 */
@WebServlet("/user/*")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024, // 1MB
    maxFileSize = 1024 * 1024 * 5,   // 5MB
    maxRequestSize = 1024 * 1024 * 10 // 10MB
)
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }
        
        switch (pathInfo) {
            case "/list":
                listUsers(request, response);
                break;
            case "/view":
                viewUser(request, response);
                break;
            case "/register":
                showRegisterForm(request, response);
                break;
            case "/login":
                showLoginForm(request, response);
                break;
            case "/logout":
                logout(request, response);
                break;
            case "/edit":
                showEditForm(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/user/list");
                break;
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }
        
        switch (pathInfo) {
            case "/register":
                register(request, response);
                break;
            case "/login":
                login(request, response);
                break;
            case "/update":
                updateUser(request, response);
                break;
            case "/delete":
                deleteUser(request, response);
                break;
            case "/uploadAvatar":
                uploadAvatar(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/user/list");
                break;
        }
    }
    
    /**
     * 显示所有用户列表
     */
    private void listUsers(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        List<User> userList = userService.getAllUsers();
        request.setAttribute("userList", userList);
        request.getRequestDispatcher("/WEB-INF/jsp/user/list.jsp").forward(request, response);
    }
    
    /**
     * 查看用户详情
     */
    private void viewUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            int id = Integer.parseInt(idStr);
            User user = userService.getUserById(id);
            if (user != null) {
                request.setAttribute("user", user);
                request.getRequestDispatcher("/WEB-INF/jsp/user/view.jsp").forward(request, response);
                return;
            }
        }
        response.sendRedirect(request.getContextPath() + "/user/list");
    }
    
    /**
     * 显示注册表单
     */
    private void showRegisterForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/user/register.jsp").forward(request, response);
    }
    
    /**
     * 处理用户注册
     */
    private void register(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String fullName = request.getParameter("fullName");
        String ageStr = request.getParameter("age");
        int age = 0;
        if (ageStr != null && !ageStr.isEmpty()) {
            try {
                age = Integer.parseInt(ageStr);
            } catch (NumberFormatException e) {
                // 使用默认值0
            }
        }
        String gender = request.getParameter("gender");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String hobby = request.getParameter("hobby");
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setFullName(fullName);
        user.setAge(age);
        user.setGender(gender);
        user.setEmail(email);
        user.setPhone(phone);
        user.setHobby(hobby);
        
        boolean success = userService.register(user);
        if (success) {
            request.setAttribute("message", "注册成功，请登录！");
            request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
        } else {
            request.setAttribute("error", "注册失败，用户名可能已存在！");
            request.setAttribute("user", user);
            request.getRequestDispatcher("/WEB-INF/jsp/user/register.jsp").forward(request, response);
        }
    }
    
    /**
     * 显示登录表单
     */
    private void showLoginForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
    }
    
    /**
     * 处理用户登录
     */
    private void login(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        User user = userService.login(username, password);
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            
            // 根据用户角色进行不同的跳转
            if ("admin".equals(user.getRole())) {
                // 管理员跳转到后台管理页面
                response.sendRedirect(request.getContextPath() + "/admin/");
            } else {
                // 普通用户跳转到博客首页
                response.sendRedirect(request.getContextPath() + "/blog/list");
            }
        } else {
            request.setAttribute("error", "用户名或密码错误！");
            request.setAttribute("username", username);
            request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
        }
    }
    
    /**
     * 处理用户退出
     */
    private void logout(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        response.sendRedirect(request.getContextPath() + "/user/login");
    }
    
    /**
     * 显示编辑表单
     */
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            int id = Integer.parseInt(idStr);
            User user = userService.getUserById(id);
            if (user != null) {
                request.setAttribute("user", user);
                request.getRequestDispatcher("/WEB-INF/jsp/user/edit.jsp").forward(request, response);
                return;
            }
        }
        response.sendRedirect(request.getContextPath() + "/user/list");
    }
    
    /**
     * 更新用户信息
     */
    private void updateUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            int id = Integer.parseInt(idStr);
            User user = userService.getUserById(id);
            if (user != null) {
                user.setUsername(request.getParameter("username"));
                user.setPassword(request.getParameter("password"));
                user.setNickname(request.getParameter("nickname"));
                user.setFullName(request.getParameter("fullName"));
                
                String ageStr = request.getParameter("age");
                if (ageStr != null && !ageStr.isEmpty()) {
                    try {
                        user.setAge(Integer.parseInt(ageStr));
                    } catch (NumberFormatException e) {
                        // 保持原值不变
                    }
                }
                
                user.setGender(request.getParameter("gender"));
                user.setEmail(request.getParameter("email"));
                user.setPhone(request.getParameter("phone"));
                user.setHobby(request.getParameter("hobby"));
                
                // 处理头像上传
                try {
                    Part filePart = request.getPart("avatar");
                    if (filePart != null && filePart.getSize() > 0) {
                        String fileName = getSubmittedFileName(filePart);
                        if (fileName != null && !fileName.isEmpty()) {
                            String extension = fileName.substring(fileName.lastIndexOf("."));
                            String newFileName = UUID.randomUUID().toString() + extension;
                            
                            String uploadDir = getServletContext().getRealPath("/uploads/avatars");
                            File uploadDirFile = new File(uploadDir);
                            if (!uploadDirFile.exists()) {
                                uploadDirFile.mkdirs();
                            }
                            
                            String filePath = uploadDir + File.separator + newFileName;
                            filePart.write(filePath);
                            
                            // 更新用户头像路径
                            user.setAvatar("/uploads/avatars/" + newFileName);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                boolean success = userService.updateUser(user);
                
                if (success) {
                    // 更新session中的用户信息
                    HttpSession session = request.getSession();
                    if (session.getAttribute("user") != null) {
                        User sessionUser = (User) session.getAttribute("user");
                        if (sessionUser.getId() == user.getId()) {
                            session.setAttribute("user", user);
                        }
                    }
                    
                    response.sendRedirect(request.getContextPath() + "/user/view?id=" + id);
                } else {
                    request.setAttribute("error", "更新失败！");
                    request.setAttribute("user", user);
                    request.getRequestDispatcher("/WEB-INF/jsp/user/edit.jsp").forward(request, response);
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/user/list");
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/user/list");
        }
    }
    
    /**
     * 处理头像上传
     */
    private void uploadAvatar(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            int id = Integer.parseInt(idStr);
            User user = userService.getUserById(id);
            
            if (user != null) {
                try {
                    Part filePart = request.getPart("avatarFile");
                    if (filePart != null && filePart.getSize() > 0) {
                        String fileName = getSubmittedFileName(filePart);
                        if (fileName != null && !fileName.isEmpty()) {
                            String extension = fileName.substring(fileName.lastIndexOf("."));
                            String newFileName = UUID.randomUUID().toString() + extension;
                            
                            String uploadDir = getServletContext().getRealPath("/uploads/avatars");
                            File uploadDirFile = new File(uploadDir);
                            if (!uploadDirFile.exists()) {
                                uploadDirFile.mkdirs();
                            }
                            
                            String filePath = uploadDir + File.separator + newFileName;
                            filePart.write(filePath);
                            
                            // 更新用户头像路径
                            user.setAvatar("/uploads/avatars/" + newFileName);
                            userService.updateUser(user);
                            
                            // 更新session中的用户信息
                            HttpSession session = request.getSession();
                            if (session.getAttribute("user") != null) {
                                User sessionUser = (User) session.getAttribute("user");
                                if (sessionUser.getId() == user.getId()) {
                                    session.setAttribute("user", user);
                                }
                            }
                            
                            // 返回JSON响应
                            response.setContentType("application/json");
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write("{\"success\":true,\"avatar\":\"" + user.getAvatar() + "\"}");
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        // 返回错误JSON响应
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("{\"success\":false,\"message\":\"上传失败\"}");
    }
    
    /**
     * 删除用户
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            int id = Integer.parseInt(idStr);
            userService.deleteUser(id);
        }
        response.sendRedirect(request.getContextPath() + "/user/list");
    }
    
    /**
     * 获取上传文件的文件名
     */
    private String getSubmittedFileName(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1);
            }
        }
        return null;
    }
} 